import _ from "lodash"
import store from "../store/store"
import User, { IUser } from "../table_operation/user_operation"

export const loginCheck = ():boolean | {} => {
    let access_token = localStorage.getItem("$ACCESS_TOKEN")
    let nick_name = localStorage.getItem("$NICK_NAME")
    if (!access_token || !nick_name) {
        return false
    } else {
        return {
            nickName: nick_name,
            accessToken: access_token,
        }
    }
}
export const executeLogin = async (nickName: string | null | undefined): Promise<any> => {
    if (!nickName) {
        nickName = localStorage.getItem("$NICK_NAME")
    }

    let userList: IUser[] = store.userList;
    if (_.isEmpty(userList)) {
        userList = await User.getAllUser()
    }
    // console.log("userList:", userList)
    let loginUser:IUser;
    let bindingUser:IUser | IUser[];
    let userFiltered = userList.filter(user => user.nickName === nickName)
    if (userFiltered.length > 1) {
        console.error("Database has more than one user named:" + nickName)
    }
    loginUser = userFiltered[0];
    store.currentUser = loginUser;

    bindingUser = userList.filter(user => user.id === loginUser.bindingId)
    if (Array.isArray(bindingUser) && bindingUser.length) {
        bindingUser = bindingUser[0]
    } else {
        console.error("Current User not bind another account!")
        bindingUser = []
    }
    store.bindingUser = bindingUser

    if (nickName) {
        localStorage.setItem("$NICK_NAME", nickName)
    }
    return store
}